import {TREEOBJ} from './tree';
export const setFullscreen = (f = true) => {
  // W3C
  let docElm = document.documentElement;
  if (f) {
    if (docElm.requestFullscreen) {
      docElm.requestFullscreen();
    } else if (docElm.mozRequestFullScreen) {
      docElm.mozRequestFullScreen();
    } else if (docElm.webkitRequestFullScreen) {
      docElm.webkitRequestFullScreen();
    } else if (docElm.msRequestFullscreen) {
      docElm.msRequestFullscreen();
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitCancelFullScreen) {
      document.webkitCancelFullScreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    }
  }
};

const tools = {
  // 格式化日期 前台传值方式  引用类.dateFormat(1402233166999,"yyyy-MM-dd hh:mm:ss")
dateFormat : (date, fmt = 'yyyy-MM-dd hh:mm:ss') => {
    let getDate = new Date(date);
    let o = {
      'M+': getDate.getMonth() + 1,
      'd+': getDate.getDate(),
      'h+': getDate.getHours(),
      'm+': getDate.getMinutes(),
      's+': getDate.getSeconds(),
      'q+': Math.floor((getDate.getMonth() + 3) / 3),
      'S': getDate.getMilliseconds()
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (let k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
      }
    }
    return fmt;
  },
  // 设置和修改cookie
  setCookie: (name, value, iDay) => {
    /* iDay 表示过期时间 name是设置cookie名称
    cookie中 = 号表示添加，不是赋值 */
    let oDate = new Date();
    oDate.setDate(oDate.getDate() + iDay);
    document.cookie = name + '=' + value + ';expires=' + oDate;
  },
  // 获取cookie
  getCookie: (name) => {
    /* 获取浏览器所有cookie将其拆分成数组 */
    let arr = document.cookie.split('; ');
    for (let i = 0; i < arr.length; i++) {
      /* 将cookie名称和值拆分进行判断 */
      let arr2 = arr[i].split('=');
      if (arr2[0] === name) {
        return arr2[1];
      }
    }
    return '';
  },
  // 清空所有cookie;
  clearCookie: () => {
    let cookie = document.cookie;
    let cookieArray = cookie.split('; '); // 将所有键值对分开
    let cookieKey = []; // 保存cookie中键值名的数组
    for (let i = 0; i < cookieArray.length; i++) {
      let keyValue = cookieArray[i].split('=');
      cookieKey[cookieKey.length] = keyValue[0]; // 将对应的cookie的键存入数组中
    }
    for (let i = 0; i < cookieKey.length; i++) {
      this.setCookie(cookieKey[i], 1, -1); // 只要将cookie的保存日期设置为-1就可以清除kookie
    }
    console.log('已经成功清除所有cookie信息！');
  },
  // 获取市下面projectId数组，传对应的节点的data.children
  getProjectId (arr = []) {
    let result = [];
    arr.forEach(item => {
      result.push(item.id);
    });
    return result;
  }
};
export default tools;

// 根据项目id获取树的数据
export const getTreeNodeById = () => {
  let treeNode = null;
  function getTreeNode (projectId) {
    const data = JSON.parse(window.localStorage.getItem('TREEDATA'));
    console.log(data);
    data.map(item => {
      console.log('===执行顺序===');
      console.log(item.id);
      if (item.id == projectId) {
        treeNode = item; // 结果赋值
      } else {
        if (item.children) {
          getTreeNode(item.children, projectId);
        }
      }
    });
  }
  console.log(getTreeNode, treeNode);
};

export function getDevData (data, deviceName) {
  let obj = null;
  data.forEach(v => {
    if (v.name == deviceName) {
      obj = v;
    }
  });
  return obj;
}

// 通过树的类型获取树节点 0 城市 1 车间 2 项目
export function getTreeDataByType (data, type = '2') {
  const arr = [];
  function getData (d) {
    d.forEach(v => {
      if (v.children && v.children.length > 0) {
        getData(v.children);
      }
      if (v.type == type) {
        arr.push(v);
      }
    });
  }
  getData(data);
  return arr;
}

export function getSiganlValue (data, deviceName, signalName, type = 'normal') {
  let signal = {};
  if (data.name == deviceName) {
    data.signalList.forEach(item => {
      if (item.name === signalName) {
        // 正常值
        if (type == 'normal') {
          signal = {
            value: item.value,
            unit: item.unit
          };
        // 状态值
        } else if (type == 'state') {
          let description = item.description.split('/');
          let value = (item.value == '1' ? description[0] : description[1]);
          signal = {
            value: value,
            unit: item.unit
          };
        }
      }
    });
  }
  return signal;
}

// 根据项目id获取node
export function getNodeById (projectId) {
  let projectItem = JSON.parse(window.localStorage.getItem('projectItem')) || [];
  let item = null;
  for (let i = 0, len = projectItem.length; i < len; i++) {
    if (projectItem[i]) {
      (projectItem[i].children || []).forEach(v => {
        if (v.id === projectId) {
          item = v;
        }
      });
    }
  }
  return item;
}

// 获取所有权限的项目id
export function getAllUserProjectId () {
  let arr = [];
  let projectItem = JSON.parse(window.localStorage.getItem('TREEOBJ')) || [];
  const obj = new TREEOBJ('pid', 'children', 'label', 0);
  const list = obj.getTreeDataList(projectItem);
  console.log(list);
  for (let i = 0, len = list.length; i < len; i++) {
    if (list[i].type == 2) {
      arr.push(list[i].id);
    }
  }
  return arr;
}

export function downloadFile (res, fileName = '默认报表名称.xlsx') {
  if (!res) { return; }
  let filename = fileName;
  if (res.headers && res.headers['content-disposition']) {
    let name = decodeURI(res.headers['content-disposition']).split('=');
    filename = name && name[1];
  }
  let blob = new Blob([res], { type: 'application/vnd.ms-excel' }); // blob 一定要加入type,不然导出的表格会是乱码，恶心的object object
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, fileName);
  } else {
    let url = window.URL.createObjectURL(blob);
    let link = document.createElement('a');
    link.style.display = 'none';
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}

// 根据key值查找树的节点
export function findTreeNode (data, key, value, callBack) {
  data.map(item => {
    if (item[key] == value) {
      callBack && (typeof callBack == 'function') && callBack(item);
    } else {
      if (item[key]) {
        findTreeNode(item['children'], key, value, callBack);
      }
    }
  });
}

export function isNumber (val) {
  let regPos = /^\d+(\.\d+)?$/; // 非负浮点数
  let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; // 负浮点数
  if (regPos.test(val) || regNeg.test(val)) {
    return true;
  } else {
    return false;
  }
}

export function loadScript (url, callback) {
  let script = document.createElement('script');
  script.type = 'text/javascript';
  script.async = 'async';
  script.src = url;
  document.querySelector('header').appendChild(script);
  if (script.readyState) { // IE
    script.onreadystatechange = function () {
      if (script.readyState == 'complete' || script.readyState == 'loaded') {
        script.onreadystatechange = null;
        callback && callback();
      }
    };
  } else { // 非IE
    script.onload = function () {
      callback && callback();
    };
  }
}

// 生成随机字符串
export function randomString (len = 32) {
  let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length;
  var pwd = '';
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

// 保留小数
export function numToFixed (val, num = 2) {
  return parseFloat(val).toFixed(num);
}

export function paramsQs (obj) {
  let str = '';
  for (let i in obj) {
    str += `${i}=${obj[i]}&`;
  }
  return str.substr(0, str.length - 1);
}

// 根据key值去查找节点
export const findTreeNodeByKeyValue = (tree, key, value) => {
  let node = null;
  function handleData (tree) {
    for (let i = 0, len = tree.length; i < len; i++) {
      if (tree[i][key] == value) {
        node = tree[i];
      } else {
        if (tree[i].children && tree[i].children.length > 0) {
          handleData(tree[i].children);
        }
      }
    }
  }
  handleData(tree);
  return node;
};

//计算旋转角度
export function getAngle( lon1, lat1, lon2,lat2) {
  const deg2rad = Math.PI / 180;
  const dlat = (lat2 - lat1) * deg2rad;
  const dlon = (lon2 - lon1) * deg2rad;
  const y = Math.sin(dlon) * Math.cos(lat2 * deg2rad);
  const x = Math.cos(lat1 * deg2rad) * Math.sin(lat2 * deg2rad) - Math.sin(lat1 * deg2rad) * Math.cos(lat2 * deg2rad) * Math.cos(dlon);
  const angle = Math.atan2(y, x) * 180 / Math.PI;
  return angle;
}

// 示例用法  
var lat1 = 39.907522; // 纬度1  
var lon1 = 116.3972333; // 经度1  
var lat2 = 31.230422; // 纬度2  
var lon2 = 121.473733; // 经度2  
  
var bearing = getAngle( lon1, lat1, lon2,lat2);  
console.log("方位角（初始方位角）是: " + bearing + "°");